import { defineStore } from 'pinia'
import { login, getUserInfo } from '@/api/user'
import tokenManager from '@/utils/tokenManager'

// 安全解析localStorage中的JSON数据
const safeParseJSON = (key, defaultValue) => {
  try {
    const value = localStorage.getItem(key)
    if (!value || value === 'undefined' || value === 'null') {
      return defaultValue
    }
    return JSON.parse(value)
  } catch (error) {
    return defaultValue
  }
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userId: localStorage.getItem('userId') || '',
    username: localStorage.getItem('username') || '',
    name: localStorage.getItem('name') || '',
    roles: safeParseJSON('userRoles', []),
    department: safeParseJSON('department', null)
  }),
  
  getters: {
    isLoggedIn: state => !!state.token && !!state.username && state.username !== 'undefined',
    isAdmin: state => state.roles.includes('ROLE_ADMIN'),
    isDepartmentHead: state => state.roles.includes('ROLE_DEPARTMENT_HEAD'),
    isResearchHead: state => state.roles.includes('ROLE_RESEARCH_HEAD'),
    isTeacher: state => state.roles.includes('ROLE_TEACHER')
  },
  
  actions: {
    // 初始化用户信息（页面刷新时调用）
    async initializeUser() {
      // 检查localStorage中的数据是否完整和有效
      const token = localStorage.getItem('token')
      const username = localStorage.getItem('username')
      
      if (!token || !username || username === 'undefined' || username === 'null') {
        // 数据不完整或无效，清除所有登录状态
        this.clearInvalidLoginState()
        return
      }
      
      // 如果已登录但没有姓名信息，则获取用户详细信息
      if (this.token && this.username && this.username !== 'undefined' && !this.name) {
        try {
          await this.getUserInfoAction()
        } catch (error) {
          // 如果获取用户信息失败，可能token已过期，清除登录状态
          this.clearInvalidLoginState()
        }
      }
    },

    // 清除无效的登录状态
    clearInvalidLoginState() {
      this.token = ''
      this.userId = ''
      this.username = ''
      this.name = ''
      this.roles = []
      this.department = null

      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('username')
      localStorage.removeItem('name')
      localStorage.removeItem('userRoles')
      localStorage.removeItem('department')
    },

    // 用户登录
    async loginAction(username, password) {
      try {
        const response = await login(username, password)
        // 响应拦截器已自动提取 ApiResponse.data 字段
        const { token, id, username: uname, roles } = response
        
        // 保存到状态
        this.token = token
        this.userId = id
        this.username = uname
        this.roles = roles
        
        // 保存到本地存储
        localStorage.setItem('token', token)
        localStorage.setItem('userId', id)
        localStorage.setItem('username', uname)
        localStorage.setItem('userRoles', JSON.stringify(roles))
        
        // 登录成功后获取用户详细信息（包括姓名）
        await this.getUserInfoAction()
        
        // 启动token管理
        tokenManager.onLogin()
        
        // 启动会话守卫
        const sessionGuard = await import('@/utils/sessionGuard')
        sessionGuard.default.start()
        
        return true
      } catch (error) {
        return false
      }
    },
    
    // 获取用户信息
    async getUserInfoAction() {
      if (!this.username || this.username === 'undefined') {
        return
      }
      
      try {
        const response = await getUserInfo(this.username)
        // 响应拦截器已自动提取 ApiResponse.data 字段
        const { name, department } = response
        this.name = name || ''
        this.department = department || null

        // 保存到本地存储
        localStorage.setItem('name', name || '')
        localStorage.setItem('department', JSON.stringify(department || null))
      } catch (error) {
        // 获取用户信息失败，继续执行
      }
    },

    // 用户登出
    async logout() {
      // 停止token管理
      tokenManager.onLogout()
      
      // 停止会话守卫
      try {
        const sessionGuard = await import('@/utils/sessionGuard')
        sessionGuard.default.stop()
      } catch (error) {
        // 停止会话守卫失败，继续执行
      }
      
      this.token = ''
      this.userId = ''
      this.username = ''
      this.name = ''
      this.roles = []
      this.department = null

      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('username')
      localStorage.removeItem('name')
      localStorage.removeItem('userRoles')
      localStorage.removeItem('department')
    },
    
    // 检查会话有效性（主动检查）
    async checkSessionValidity() {
      if (!this.isLoggedIn) {
        return false
      }
      
      try {
        // 通过获取用户信息来验证会话是否有效
        await this.getUserInfoAction()
        return true
      } catch (error) {
        this.clearInvalidLoginState()
        return false
      }
    }
  }
})
